package com.zkingsoft.thread;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.dingtalk.open.client.api.model.corp.MessageBody;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Body.Form;
import com.dingtalk.open.client.api.model.corp.MessageBody.OABody.Head;
import com.dingtalk.open.client.api.model.corp.MessageType;
import com.zkingsoft.dao.BugDao;
import com.zkingsoft.dao.TaskDao;
import com.zkingsoft.dingding.Env;
import com.zkingsoft.dingding.Vars;
import com.zkingsoft.dingding.auth.AuthHelper;
import com.zkingsoft.dingding.message.LightAppMessageDelivery;
import com.zkingsoft.dingding.message.MessageHelper;
import com.zkingsoft.model.Bug;
import com.zkingsoft.model.Task;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.services.BugService;
import com.zkingsoft.services.TaskService;

/**
 * 
 * @description 发送与bug相关的消息通知线程类
 * @author chenxianzi
 * @date 2016年12月15日
 */
public class SendBugMsgsThread implements Runnable {
	
	BugService bugService = null;
	BugDao bugDao = null;
	Long bugid = null;
	String bgColor = null;
	String title = null;
	//发送任务OA消息提醒，OA消息体,map对象中请放入两个key：key,value
	List<Map<String, String>> msgList = null;
	boolean isCreateUser ; //消息发送个谁，true:创建人，false:指派人
	boolean flag = false;
	
	public SendBugMsgsThread(BugService bugService, Long bugid, 
			String bgColor, String title, boolean isCreateUser,List<Map<String, String>> msgList) {
		this.bugService = bugService;
		this.bugid = bugid;
		this.bgColor = bgColor;
		this.title = title;
		this.isCreateUser = isCreateUser;
		this.msgList = msgList;
	}
	
	public SendBugMsgsThread(BugDao bugDao,Long bugid, 
			String bgColor, String title, boolean isCreateUser, List<Map<String, String>> msgList) {
		this.bugDao = bugDao;
		this.bugid = bugid;
		this.bgColor = bgColor;
		this.title = title;
		this.isCreateUser = isCreateUser;
		this.msgList = msgList;
	}



	@Override
	public void run() {
			if(bugService!=null){
				flag = sendOaMsgs();
			}
			if(bugDao!=null){
				flag = sendOaMsgsInService();
			}			
	}	
	
	/**
	 * @Description:批量发送oa通知,供controller层使用
	 * @author: chenxianzi
	 * @param taskIds 新增的任务id集合
	 * 返回类型 void
	 * @date 2016年12月15日
	 */
	public boolean sendOaMsgs(){
		try {
			List<Bug> bugs = bugService.findBugAndDdUserId(bugid);
			if(bugs!=null && bugs.size() > 0){					
				//循环发送OA消息
				String accessToken = AuthHelper.getAccessToken();//获取accessToken
				String toUsers = "";
				String toParties = Vars.TO_PARTY;
				String agentId = Vars.AGENT_ID;
				for (Bug bug : bugs) {					
					//创建oa消息
					MessageBody.OABody oaBody = createOaMsg(bug);
					// 发送微应用消息
					//给创建人或者指派人发送
					if(isCreateUser){
						toUsers = bug.getCreateValidateCode();
					}else{
						toUsers = bug.getUserValidateCode();
					}
					LightAppMessageDelivery lightAppMessageDelivery = new LightAppMessageDelivery(toUsers, toParties, agentId);
					lightAppMessageDelivery.withMessage(MessageType.OA, oaBody);					
					MessageHelper.send(accessToken, lightAppMessageDelivery);
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;	
	}
	
	
	/**
	 * @Description:批量发送oa通知,供Service层使用
	 * @author: chenxianzi
	 * @param bugid 新增的bug的id
	 * 返回类型 boolean
	 * @date 2016年12月15日
	 */
	public boolean sendOaMsgsInService(){
		try {
			List<Bug> bugs = bugDao.selectBugAndDdUserId(bugid);
			if(bugs!=null && bugs.size() > 0){	
				//发送OA消息
				String accessToken = AuthHelper.getAccessToken();//获取accessToken
				String toUsers =  "";
				String toParties = Vars.TO_PARTY;
				String agentId = Vars.AGENT_ID;
				//循环发送OA消息
				for (Bug bug : bugs) {
					//创建oa消息
					MessageBody.OABody oaBody = createOaMsg(bug);
					if(isCreateUser){
						toUsers = bug.getCreateValidateCode();
					}else{
						toUsers = bug.getUserValidateCode();
					}					
					LightAppMessageDelivery lightAppMessageDelivery = new LightAppMessageDelivery(toUsers, toParties, agentId);
					lightAppMessageDelivery.withMessage(MessageType.OA, oaBody);
					MessageHelper.send(accessToken, lightAppMessageDelivery);
					//Service中只有新增任务的时候才会发送消息通知，此时还没有关注者
				}
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;	
	}
	
	/**
	 * @Description:创建OA消息
	 * chenxianzi
	 * @param task
	 * @return
	 * 返回类型 MessageBody.OABody
	 * @date 2016年12月15日
	 */
	public MessageBody.OABody createOaMsg(Bug bug){
		SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_DD);
		MessageBody.OABody oaBody = new MessageBody.OABody();
        oaBody.setMessage_url(Env.LOOK_BUGMESSAGE + bug.getId());
        oaBody.setPc_message_url(Env.LOOK_BUGMESSAGE + bug.getId());
        //头部
        Head head = new Head();
        head.setText("");
        head.setBgcolor(bgColor);
        oaBody.setHead(head);
        //内容
        Body body = new Body();
        body.setTitle(bug.getTitle());
        List<Form> formList = new ArrayList<Form>();
        if(msgList == null){
        	Form form6 = new Form();
        	form6.setKey("bug标题");
        	form6.setValue(bug.getTitle());
            formList.add(form6);
            Form form7 = new Form();
            form7.setKey("所属模块");
            form7.setValue(bug.getInterfaceName());
            formList.add(form7);
        	Form form4 = new Form();
            form4.setKey("bug状态");
            form4.setValue(title);
            formList.add(form4);
            Form form5 = new Form();
            Form form2 = new Form();
            form2.setKey("解决方案");
            form2.setValue(bug.getType());
            formList.add(form2);
            form5.setKey("指派人");
            form5.setValue(bug.getAssignUserName());
            formList.add(form5);
            Form form = new Form();
            form.setKey("创建人");
            form.setValue(bug.getCreateUserName());
            formList.add(form);
            Form form1 = new Form();
            form1.setKey("bug等级");
            form1.setValue(bug.getGrade()+"级bug");
            formList.add(form1);
            Form form3 = new Form();
            form3.setKey("创建时间");
            form3.setValue(sdf.format(bug.getCreateTime()));
            formList.add(form3);
        }else{
        	for (Map<String, String> map : msgList) {
				Form form = new Form();
				form.setKey(map.get("key"));
				form.setValue(map.get("value"));
				formList.add(form);
			}
        }
        body.setForm(formList);
        oaBody.setBody(body);
		return oaBody;
	}

	public BugService getBugService() {
		return bugService;
	}

	public void setBugService(BugService bugService) {
		this.bugService = bugService;
	}

	public BugDao getBugDao() {
		return bugDao;
	}

	public void setBugDao(BugDao bugDao) {
		this.bugDao = bugDao;
	}

	public Long getBugid() {
		return bugid;
	}

	public void setBugid(Long bugid) {
		this.bugid = bugid;
	}

	public String getBgColor() {
		return bgColor;
	}

	public void setBgColor(String bgColor) {
		this.bgColor = bgColor;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public List<Map<String, String>> getMsgList() {
		return msgList;
	}

	public void setMsgList(List<Map<String, String>> msgList) {
		this.msgList = msgList;
	}

	public boolean isCreateUser() {
		return isCreateUser;
	}

	public void setCreateUser(boolean isCreateUser) {
		this.isCreateUser = isCreateUser;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}
	      
	
	
}
